package myky.com.doctorapp.ui

import android.content.Intent
import android.os.Bundle
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewTreeObserver
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.foamtrace.photopicker.ImageCaptureManager
import com.foamtrace.photopicker.PhotoPickerActivity
import com.gyf.barlibrary.ImmersionBar

import kotlinx.android.synthetic.main.activity_remote_submit.*
import kotlinx.android.synthetic.main.public_common_title.*
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.ImageAdapter
import myky.com.doctorapp.base.BaseActivity

import myky.com.doctorapp.contract.ImageUploadContract
import myky.com.doctorapp.contract.RemoteSubmitActivityContract
import myky.com.doctorapp.entity.*
import myky.com.doctorapp.presenter.RemoteSubmitActivityPresenter
import myky.com.doctorapp.utils.AddPhotoUtils
import myky.com.doctorapp.utils.CheckTextUtils
import myky.com.doctorapp.utils.Constants
import myky.com.doctorapp.utils.ImageUtils
import myky.com.doctorapp.wight.SelfDialog

/**
 * Description:远程提交界面
 * @author wuyangwuyang
 * Created by 2019/1/11 on 10:25
 */
class RemoteSubmitActivity : BaseActivity<RemoteSubmitActivityPresenter, RemoteAutoFillEntity.DataBean>(), RemoteSubmitActivityContract.View, View.OnClickListener, BaseQuickAdapter.OnItemChildClickListener,ImageUploadContract {



    var doctorId: Int = 0
    var diseaseId:Int=0
    var freq:Int=0
    var known:Int=0
    lateinit var texts: TextView
    var fullString: String? = null
    // 相机拍照处理类
    var captureManager: ImageCaptureManager? = null
    lateinit var imagePathsResult :MutableList<String>
    lateinit var remoteSubmit: RemoteSubmitEntity
    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.activity_remote_nickName -> {
                texts = findViewById(R.id.activity_remote_nickName_tv)
                val bundle = Bundle()
                bundle.putString(Constants.INTENTTYPE, Constants.DISEASETYPE)
                bundle.putInt(Constants.DOCTORID, doctorId)
                startActivityForResult(ListActivity::class.java, bundle, Constants.INTENTCODE)
            }

            R.id.activity_remote_health ->
                startActivity(HealthRecordActivity::class.java)
            R.id.activity_remote_visit -> {
                texts = findViewById(R.id.activity_remote_visit_tv)
                val bundle = Bundle()
                bundle.putString(Constants.INTENTTYPE, Constants.VISITTYPE)
                startActivityForResult(ListActivity::class.java, bundle, Constants.INTENTCODE)
            }
            R.id.activity_remote_iskonow -> {
                texts = findViewById(R.id.activity_remote_iskonow_tv)
                val bundle = Bundle()
                bundle.putString(Constants.INTENTTYPE, Constants.ISKONOWTYPE)
                startActivityForResult(ListActivity::class.java, bundle, Constants.INTENTCODE)
            }

            R.id.activity_remote_full -> {
                if (fullString != null) {
                    activity_remote_et.setText(fullString)
                    showShortToast(resources.getString(R.string.RemoteSubmit_success))
                } else {
                    showShortToast(resources.getString(R.string.RemoteSubmit_inputnull))
                }
            }
            R.id.ll_remote_explain->{

                openRightMenu(takephoto_drawerlayout)
            }
            R.id.activity_remote_submit->
            {
                checkInputs()


            }
            R.id.backLayout -> onBackPressed()
        }

    }


    lateinit var imageAdapter: ImageAdapter
    private lateinit var imagelist: MutableList<ImageEntity>
    override fun reloadActivity() {
    }

    override fun getPresenter() = RemoteSubmitActivityPresenter()
    override fun injectTarget(): View = findViewById(R.id.remote_submit_lin)

    override fun initData() {
        var bundle = this.intent.extras
        doctorId = bundle.getInt(Constants.DOCTORID)
        mPresenter.pisRepeat(doctorId)
    }

    override fun initView() {

        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)
                .titleBar(R.id.remote_title)
                .init()
        conmonTitleTextView.text = getText(R.string.RemoteDoctorList_title)
        captureManager = ImageCaptureManager(this)
        imagelist = ArrayList()
        imagelist.add(ImageEntity(""))
        imageAdapter = ImageAdapter(imagelist)
        activity_remote_recycler.layoutManager = GridLayoutManager(this, 3)
        activity_remote_recycler.adapter = imageAdapter
        imageAdapter.onItemChildClickListener = this
        activity_remote_nickName.setOnClickListener(this)
        activity_remote_health.setOnClickListener(this)
        activity_remote_visit.setOnClickListener(this)
        activity_remote_full.setOnClickListener(this)
        activity_remote_iskonow.setOnClickListener(this)
        activity_remote_submit.setOnClickListener(this)
        ll_remote_explain.setOnClickListener(this)
        backLayout.setOnClickListener(this)
        initRightMenu(takephoto_drawerlayout)

    }

    override fun getContenView(): Int = R.layout.activity_remote_submit

    override fun showDataSuccess(datas: RemoteAutoFillEntity.DataBean?) {
        if (datas != null) {
            activity_remote_nickName_tv.text = datas.diseaseName
            diseaseId=datas.diseaseId
            if (datas.freq!=null) {
                activity_remote_visit_tv.text = resources.getStringArray(R.array.remote_freq)[datas.freq]
                freq=datas.freq
            }
            if (datas.known!=null) {
                activity_remote_iskonow_tv.text = resources.getStringArray(R.array.remote_known)[datas.known]
                known=datas.known
            }
            if (datas.content != null) {
                fullString = datas.content
            }
        }
    }

    /**
     * 远程提交成功结果
     */
    override fun showSubmitData(submitEntity: RemoteRepeatEntity.PayLoadBean) {

        hideLoading()
        val bundle = Bundle()
        bundle.putInt(Constants.DOCTORID,doctorId)
        bundle.putInt(Constants.REMOTEID,submitEntity.id)
        startActivity(SuccessfulActivity::class.java,bundle)

    }

    /**
     * 判断健康档案是否完善
     */
    override fun showResult(recordEntity: RecordEntity.PayLoadBean) {

        val isWhole=recordEntity.isWhole
        if (isWhole){
            ImageUtils.upload(this,imagelist,this);
        }else{
            val selfDialog = SelfDialog(this)
            selfDialog.setTitle(resources.getString(R.string.RemoteSubmit_healthrepeat))
            selfDialog.setYesOnclickListener(resources.getString(R.string.set_time_dialog_btn_qx), SelfDialog.onYesOnclickListener { selfDialog.dismiss() })
            selfDialog.setNoOnclickListener(resources.getString(R.string.set_time_dialog_btn_qd)) { selfDialog.dismiss() }
            selfDialog.show()
        }
    }

    /**
     * 检测远程提交输入内容
     */
    private fun checkInputs() {

        var diseaseType = activity_remote_nickName_tv.text.toString()
        var visit = activity_remote_visit_tv.text.toString()
        var iskonow = activity_remote_iskonow_tv.text.toString()
        var describe = activity_remote_et.text.toString().trimStart().trimEnd()
        var mobile = activity_remot_mobile_et.text.toString()
        if(TextUtils.isEmpty(diseaseType)){
            showCenterToast(R.string.remote_submit_disease)
            return
        }
        if (TextUtils.isEmpty(visit)){
            showCenterToast(R.string.remote_submit_visit)
            return
        }
        if (TextUtils.isEmpty(iskonow)){
            showCenterToast(R.string.remote_submit_iskonow)
            return
        }
        if (describe.length<8){
            showCenterToast(R.string.remote_submit_desmin)
            return
        }
        if(describe.length>500){
            showCenterToast(R.string.remote_submit_desmax)
            return
        }
        if (!CheckTextUtils.isMobileNumber(mobile)){
            showCenterToast(R.string.remote_submit_mobile)
            return
        }
        remoteSubmit=RemoteSubmitEntity()
        remoteSubmit.content=describe
        remoteSubmit.diseaseId=diseaseId
        remoteSubmit.diseaseName=diseaseType
        remoteSubmit.doctorId=doctorId
        remoteSubmit.freq=freq
        remoteSubmit.known=known
        remoteSubmit.phone=mobile
        remoteSubmit.remoteSource=0
        remoteSubmit.version="v2.0"
        mPresenter.ishealthperfect()
    }

    /**
     * 是否有重复的远程未结束
     */
    override fun showRepeat(remoteRepeatEntity: RemoteRepeatEntity.PayLoadBean) {
        val code=remoteRepeatEntity.id
              if (code==900){
                  //没有获取上传远程填充内容
                  mPresenter.findSubmitData(doctorId)
        }else if (code==901){
                 //有，弹窗提示有重复确定退出
                  val selfDialog = SelfDialog(this)
                  selfDialog.setTitle(resources.getString(R.string.RemoteSubmit_hintagain))
                  selfDialog.setMessage(resources.getString(R.string.RemoteSubmit_isrepeat))
                  selfDialog.setYesOnclickListener(resources.getString(R.string.set_time_dialog_btn_qx), SelfDialog.onYesOnclickListener {
                      finish()
                      selfDialog.dismiss()
                  })

                  selfDialog.setNoOnclickListener(null) { selfDialog.dismiss() }
                  selfDialog.show()

        }

    }
    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        if (imagelist[position].path == "") {
            AddPhotoUtils.getPhotos(this, 31, 0, 9, ArrayList<String>(), 1)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == RESULT_OK) {
            when (requestCode) {
                Constants.INTENTCODE->{
                    var bundle = data.extras
                    var stringExtra = bundle.getString(Constants.RESULTDATE)
                    if (bundle.containsKey(Constants.DISEASETYPE)){
                        diseaseId=bundle.getInt(Constants.DISEASETYPE)
                    }
                    if (bundle.containsKey(Constants.VISITTYPE)){
                        freq=bundle.getInt(Constants.VISITTYPE)
                    }
                    if (bundle.containsKey(Constants.ISKONOWTYPE)){
                        known=bundle.getInt(Constants.ISKONOWTYPE)
                    }
                    if (stringExtra!=null){
                       texts.text=stringExtra
                    }

                }
                Constants.CASE_MEDICALRECORD -> {
//                    imagelist.clear()
//                    imagelist.addAll(StringFileUtils.getImgList())
//                    val deletePath = data.getStringExtra("deletePath")
//                    cameraList.remove(deletePath)
//                    val strings = java.util.ArrayList<String>()
//                    for (x in 0 until imagelist.size - 1) {
//                        strings.add(imagelist.get(x).getPath())
//                    }
                }
                Constants.TAKE_CAMERA -> {

                    val path = data.getStringExtra(Constants.IMAGEPATH)
                    //扫描及时更新新相册
                    captureManager?.galleryAddPic(path)
                    imagelist.add(ImageEntity(path))
//                    val intent = Intent(context, AddTime_MedicalRecordActivity::class.java)
//                    intent.putExtra("photoLists", takePhotos)
//                    intent.putExtra("FROM_TYPE", Constants.NEW_BESPEAK_TYPE)
//                    intent.putExtra("OPERATION_TYPE", ADDTIME_RESULTCODE)
//                    startActivityForResult(intent, ADDTIME_RESULTCODE)
                }

                Constants.TAKE_ALBUM -> {
                    if (data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT) != null) {
                        val data1 = data.data


                        imagePathsResult = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)
                        for (s in imagePathsResult) {
                            imagelist.add(ImageEntity(s))


                        }

//                        val intent = Intent(context, AddTime_MedicalRecordActivity::class.java)
//                        intent.putExtra("photoLists", imagePathsResult)
//                        intent.putExtra("FROM_TYPE", Constants.NEW_BESPEAK_TYPE)
//                        intent.putExtra("OPERATION_TYPE", ADDTIME_RESULTCODE)
//                        startActivityForResult(intent, ADDTIME_RESULTCODE)
                    }
                }
            }
        }
        imageAdapter.notifyDataSetChanged()
    }


    /**
     * 本地图片上传成功
     */
    override fun uploadSuccess(result: List<String>) {
        var remotePhotos :MutableList<RemoteSubmitEntity.RemotePhotosBean>
        remotePhotos=ArrayList()
        for (s in result) {
            var remotePhotosBean=RemoteSubmitEntity.RemotePhotosBean()
            remotePhotosBean.checkDate="2019-03-04"
            remotePhotosBean.pictureMD5=s
            remotePhotos.add(remotePhotosBean)
        }

        remoteSubmit.remotePhotos=remotePhotos

        mPresenter.pcreateRemote(remoteSubmit)
    }

    /**
     * 本地图片上传失败
     */
    override fun uploadFail(msg: String) {
        hideLoading()
        showShortToast(msg)
    }

    override fun onBackPressed() {
        if (takephoto_drawerlayout.isDrawerVisible(Gravity.RIGHT))
        {
            //关闭如何拍照侧滑提示
            closeRightMenu(takephoto_drawerlayout)
        }else{
            //判断是否有输入内容和上传资料
            if (!TextUtils.isEmpty(activity_remote_et.text)||imagelist.size>1)
            {
                val selfDialog = SelfDialog(this)
                selfDialog.setTitle(getXmlString(R.string.is_exit))
                selfDialog.setMessage(getXmlString(R.string.exit_prompt))
                selfDialog.setYesOnclickListener(getXmlString(R.string.set_time_dialog_btn_qx), SelfDialog.onYesOnclickListener {
                    finish()
                    selfDialog.dismiss()
                })
                selfDialog.setNoOnclickListener(getXmlString(R.string.set_time_dialog_btn_qd)) { selfDialog.dismiss() }
                selfDialog.show()
            }else{
              super.onBackPressed()
            }
        }

    }
    /**
     * 开启右侧侧滑菜单
     */
    fun openRightMenu(takephoto_drawerlayout: DrawerLayout) {
        takephoto_drawerlayout.openDrawer(Gravity.RIGHT)
        takephoto_drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
                Gravity.RIGHT)
    }

    /**
     * //关闭右边侧滑菜单
     */

    fun closeRightMenu(takephoto_drawerlayout: DrawerLayout) {
        takephoto_drawerlayout.closeDrawer(Gravity.RIGHT)
        takephoto_drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.RIGHT)
    }

    /**
     * //初始化侧滑菜单
     */
    fun initRightMenu(takephoto_drawerlayout: DrawerLayout) {
        takephoto_drawerlayout.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                takephoto_drawerlayout.viewTreeObserver.removeOnPreDrawListener(this)
                return false
            }
        })
        takephoto_drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.RIGHT)
        takephoto_drawerlayout.setDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {

            }

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {

            }

            override fun onDrawerOpened(drawerView: View) {
                takephoto_drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
            }

            override fun onDrawerClosed(drawerView: View) {
                takephoto_drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                        Gravity.RIGHT)
            }
        })
    }


}
